from django.db import transaction
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.views.decorators.csrf import csrf_protect
import json
import traceback

def www_required(view_func):
  """Decorator makes sure URL is accessed over www."""
  def _wrapped_view_func(request, *args, **kwargs):
      if request.META.get('HTTP_HOST') == 'spargame.com':
          request_url = request.build_absolute_uri(request.get_full_path())
          www_url = request_url.replace('http://', 'http://www.')
          return HttpResponseRedirect(www_url)
      return view_func(request, *args, **kwargs)
  return _wrapped_view_func

def csrf_www_transaction(ajax=False, check_auth=False):
  def fdec(view_func):
    @csrf_protect
    @www_required
    @transaction.commit_manually
    def wrap(request):
      return processRequest(request, view_func, transactional=True, check_auth=check_auth, ajax=ajax)
    return wrap
  return fdec

def csrf_www(ajax=False, check_auth=False):
  def fdec(view_func):
    @csrf_protect
    @www_required
    def wrap(request):
      return processRequest(request, view_func, check_auth=check_auth, ajax=ajax)
    return wrap
  return fdec

def processRequest(request, view_func, ajax=False, check_auth=False, transactional=False):
  player = None
  if check_auth:
    try:
      player = request.user.get_profile()
    except Exception:
      return render_to_response('unregistered.html', {}, context_instance=RequestContext(request))
  try:
    result = view_func(request, player)
    if transactional and result and 'errors' in result and result['errors']:
      transaction.rollback()
    elif transactional:
      transaction.commit()
    if ajax:
      return HttpResponse(json.dumps(result), mimetype="application/json")
    elif result and 'response_redirect' in result:
      return HttpResponseRedirect(result['response_redirect'])
    elif result and 'forwarding_page' in result:
      return render_to_response(result['forwarding_page'], result, context_instance=RequestContext(request))
  except Exception:
    traceback.print_exc()
    result = {'errors': 'Internal error occured. Please retry'}
    if transactional:
      transaction.rollback()
  return HttpResponse(result)
